package com.ty.game.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;

/**
 * 拦截器
 * <p>
 * 要使filter生效 在 主启动类加入注解 {@code @ServletComponentScan}
 *
 * @author: Troy.Chen(失足程序员, 15388152619)
 * @version: 2021-08-05 10:37
 **/
@Slf4j
@WebFilter(filterName = "tokenFilter", urlPatterns = "/logTest/*")
public class TokenFilter implements Serializable, Filter {

    private static final long serialVersionUID = 1L;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("TokenFilter init {}", filterConfig.getFilterName());
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("TokenFilter doFilter 我拦截到了请求");
        final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//        log.info("TokenFilter doFilter",((HttpServletRequest)request).getHeader("token"));
        final Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String s = headerNames.nextElement();
            log.info(s + " = " + httpServletRequest.getHeader(s));
        }
        /*输出*/
//        response.getWriter().print("505");
        /*继续执行*/
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("TokenFilter destroy");
    }

}
